package com.lml.leetcode;

import java.util.Arrays;

/**
 * @author Administrator
 * @date 2020/3/20 19:28
 * Description:
 */
public class DemoTest04 {

    public static void main(String[] args) {
        int[] nums1 = {2, 3, 1};
        int[] nums2 = {8, 9};
        double result = findMedianSortedArrays(nums1, nums2);
        System.out.println(result);
    }

    /**
     * 4. 寻找两个有序数组的中位数
     * https://leetcode-cn.com/problems/median-of-two-sorted-arrays/
     *
     * @param nums1 数组1
     * @param nums2 数组2
     * @return
     */
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        //创建一个新数组,用来将两个数组合并进来
        int[] nums = new int[nums1.length + nums2.length];
        //复制数组
        System.arraycopy(nums1, 0, nums, 0, nums1.length);
        System.arraycopy(nums2, 0, nums, nums1.length, nums2.length);
        //给数组排序
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));
        int length = nums.length;
        return length % 2 == 0 ? (double) (nums[(length / 2) - 1] + nums[length / 2]) / 2 : (double) nums[(length - 1) / 2];
    }
}
